package myJs.implicits

import japgolly.scalajs.react.Callback
import myJs.myPkg.jquery._
import org.scalajs.dom.{Element, Event}

import scala.scalajs.js
import myJs.Implicits._
import myJs.myPkg.{BootstrapValidator, Select2Options}
import scalatags.Text.all.s

/**
 * Created by Administrator on 2020/1/16
 */
trait MyJqueryTool {

  implicit class MyJquery(jq: JQuery) {

    def myVal = {
      if (jq.`val`() == null || js.isUndefined(jq.`val`())) {
        ""
      } else jq.`val`().toString
    }

    def select2Val = {
      if (jq.data("select2").isDefined) {
        jq.select2("data").asInstanceOf[js.Array[JDJAn]].map { dict =>
          dict("text").toString
        }
      } else {
        js.Array[String]()
      }

    }

    def mySelect2(options: Select2Options) = {
      if (jq.data("select2").isDefined) {
        jq.select2("destroy")
      }
      jq.empty().select2(options)
    }

    def dataValue = {
      jq.attr("data-value").get
    }

    def outerHTML = {
      jq.prop("outerHTML")
    }

    def select2Val(vs: js.Array[String]) = {
      jq.`val`(vs).trigger("change")
    }

    def select2Val(v: String) = {
      jq.`val`(v).select2()
    }

    def myCss(propertyName: String) = {
      myCsses(propertyName).headOption.getOrElse("")
    }

    def myCsses(propertyName: String) = {
      jq.mapElems { y =>
        $(y).css(propertyName)
      }
    }

    def findInputByName(name: String) = {
      jq.find(s":input[name='${name}']")
    }

    def findInputByValue(value: String) = {
      jq.find(s":input[value='${value}']")
    }

    def nameAttr = {
      jq.attr("name").getOrElse("")
    }

    def setChecked = {
      jq.prop("checked", true)
    }

    def isChecked = {
      jq.prop("checked").get.toString.toBoolean
    }

    def bv = {
      jq.data("bootstrapValidator").get.asInstanceOf[BootstrapValidator]
    }

    def dataBeforeValue = {
      jq.attr("data-beforeValue").getOrElse("")
    }

    def isVisible = {
      jq.is(":visible")
    }

    def getFilterDataFieldName= {
      jq.attr("filter-data-field").get
    }

    def idAttr={
      jq.attr("id").get
    }

    def offThenOn(events: String, handler: EventHandler) = {
      jq.off(events).on(events, handler)
    }

    def myOn(events: String, handler: js.ThisFunction1[Element, Event, Callback]) = {
      val useHandler = (ele: Element, eve: Event) => handler(ele, eve).runNow()
      jq.on(events, useHandler)
    }

    def myOn(events: String, handler: js.Function1[Event, Callback]) = {
      val useHandler = (e: Event) => handler(e).runNow()
      jq.on(events, useHandler)
    }

    def myOffThenOn(events: String, handler: js.Function1[Event, Callback]) = {
      val useHandler = (e: Event) => handler(e).runNow()
      jq.off(events).on(events, useHandler)
    }

  }

}
